<template>
  <div class="user-edit">
    <!-- Drawer抽屉 -->
    <Drawer :title="title" v-model="visible" width="500" draggable :mask-closable="type=='0'">
      <div :style="{maxHeight: maxHeight}" class="drawer-content">
        <div class="user-title">
          <div class="info-title">基本信息</div>
          <Avatar :src="userForm.avatar" size="large" v-show="type!='2'" />
        </div>
        <Form ref="form" :model="userForm" :rules="formValidate" :label-width="120">
          <FormItem label="登录账号(手机)" prop="mobile">
            <Input v-model="userForm.mobile" autocomplete="off" :maxlength="16" v-show="type == 2"/>
            <span v-show="type != 2">{{userForm.mobile}}</span>
          </FormItem>
          <FormItem label="用户名" prop="real_name">
            <Input v-model="userForm.real_name" />
          </FormItem>
          <FormItem label="性别">
            <Select v-model="userForm.sex">
              <Option :value="1">男</Option>
              <Option :value="0">女</Option>
            </Select>
          </FormItem>
          <FormItem label="所属部门">
            <Select v-model="userForm.organization_id" prefix="ios-home" filterable>
              <Option v-for="item in organizationList" :key="item.id" :value="item.id">{{ item.organization_name }}
              </Option>
            </Select>
          </FormItem>
          <FormItem label="职称/岗位" prop="jobs">
            <Input v-model="userForm.jobs" />
          </FormItem>
          <FormItem label="用户角色" v-show="type != 2">
            <Button type="dashed" v-for="(item, index) in roleName" :key="index">{{roleName[index]}}</Button>
          </FormItem>
          <FormItem label="角色分配" prop="rolelist" v-show="type != 0">
            <Select v-model="userForm.rolelist" multiple>
              <Option
                v-for="item in roleList"
                :value="item.id"
                :key="item.id"
                :label="item.name"
              >
                <span style="margin-right:10px;">{{ item.name }}</span>
                <span style="color:#ccc;">{{ item.description }}</span>
              </Option>
            </Select>
          </FormItem>
          <FormItem label="用户类型">
            <Select v-model="userForm.is_superuser" placeholder="请选择">
              <Option :value="0">普通用户</Option>
              <Option :value="1">管理员</Option>
            </Select>
          </FormItem>
          <!-- <FormItem label="头像">
            <upload-pic-input v-model="form.avatar"></upload-pic-input>
          </FormItem> -->
          <FormItem label="邮箱" prop="e_mail">
            <Input v-model="userForm.e_mail" />
          </FormItem>
        </Form>
      </div>
      <div class="drawer-footer br" v-show="type!='0'">
        <Button type="primary" :loading="submitLoading" @click="submit">提交</Button>
        <Button @click="visible = false">取消</Button>
      </div>
    </Drawer>
  </div>
</template>

<script>
import { addUser, editUser } from "@/api/index";
import { getOrganization, getAllRoles, register, createUserRole, getRoleByUserId, updateUser, deleteRoleByUserId } from "@/api/users";
import { validateMobile, validateOrganization } from "@/libs/validate";
import uploadPicInput from "@/views/my-components/xboot/upload-pic-input";
export default {
  name: "user",
  components: {
    uploadPicInput,
  },
  props: {
    value: {
      type: Boolean,
      default: false
    },
    data: {
      type: Object
    },
    type: {
      /**
       * '1': 编辑用户
       * '2': 添加用户
       * '0': 用户详情
       */
      type: String,
      default: "0"
    }
  },
  data() {
    return {
      visible: this.value,
      title: "",
      passColor: "",
      submitLoading: false,
      maxHeight: 510,
      organizationList: [], // 系统所有部门列表
      roleList: [],         // 系统所有角色列表
      roleName: [],         // 当前用户角色名称
      userForm: {
        mobile: '',
        real_name: '',
        organization_id: null,
        jobs: '',
        is_superuser: 0,
        sex: 1,
        rolelist: [],
      },
      formValidate: {
        // 表单验证规则
        real_name: [
          { required: true, message: "请输入姓名", trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: validateMobile, trigger: "blur" }
        ],
        e_mail: [
          { type: "email", message: "邮箱格式不正确" }
        ],
        organization_id: [
          {validator: validateOrganization, trigger: "blur"}
        ],
        jobs: [
          {required: true, message: "岗位不能为空", trigger: "blur"}
        ],
      },
      
    };
  },
  methods: {
    init() {
      this.getOrganizations();
      this.getRoleList();
    },
    // 获取所有的角色
    getRoleList() {
      getAllRoles().then(res => {
        if (res.code == 0) {
          this.roleList = res.data;
        }
      });
    },
    // 获取所有部门
    getOrganizations() {
      getOrganization().then(res => {
        if (res.code === 0) {
          this.organizationList.push(...res.data.rows);
        }
      })
    },
    submit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.type == "1") {
            // 编辑
            this.submitLoading = true;
            let params = {
              id: this.userForm.id,
              real_name: this.userForm.real_name,
              organization_id: this.userForm.organization_id,
              jobs: this.userForm.jobs,
              is_superuser: this.userForm.is_superuser,
              sex: this.userForm.sex,
              e_mail: this.userForm.e_mail,
            }
            // 当前用户的角色有变化，删除原用户-角色对应表数据，新增新的角色
            if (this.userForm.rolelist.length > 0) {
              deleteRoleByUserId({userId: this.userForm.id}).then(res => {
                const user_id = this.userForm.id;
                const roleIds = this.userForm.rolelist;
                for (let i=0; i<roleIds.length; i++) {
                  createUserRole({user_id, role_id:roleIds[i]})
                }
              })
            } 
            updateUser(params).then(res => {
              this.submitLoading = false;
              if (res.code === 0) {
                this.$Message.success(res.message);
                this.$emit("on-submit", true);
                this.visible = false;
              }
            });
          } else {
            // 添加
            this.submitLoading = true;
            let params = {
              mobile: this.userForm.mobile,
              real_name: this.userForm.real_name,
              organization_id: this.userForm.organization_id,
              jobs: this.userForm.jobs,
              is_superuser: this.userForm.is_superuser,
              sex: this.userForm.sex,
              e_mail: this.userForm.e_mail,
              avatar: 'https://i.loli.net/2019/04/28/5cc5a71a6e3b6.png'
            }
            register(params).then(res => {
              this.submitLoading = false;
              if (res.code === 0) {
                this.$Message.success(res.message);
                const user_id = res.data.id;
                const roleIds = this.userForm.rolelist;
                for (let i=0; i<roleIds.length; i++) {
                  createUserRole({user_id, role_id:roleIds[i]})
                }
                this.$emit("on-submit", true);
                this.visible = false;
              } else {
                this.$Message.error(res.message);
              }
            });
          }
        }
      });
    },
    setCurrentValue(value) {
      if (value === this.visible) {
        return;
      }
      if (this.type == "1") {
        this.title = "编辑用户";
        this.maxHeight = Number(document.documentElement.clientHeight - 121) + "px";
      } else if (this.type == "2") {
        this.title = "添加用户";
        this.maxHeight = Number(document.documentElement.clientHeight - 121) + "px";
      } else {
        this.title = "用户详情";
        this.maxHeight = "100%";
      }
      // 清空数据
      this.$refs.form.resetFields();
      if (this.type == "0" || this.type == "1") {
        // 回显数据
        this.getRoleList();
        let data = this.data;
        let selectRolesId = [];
        getRoleByUserId({userId: data.id}).then(res => {
          if (res.code === 0) {
            this.roleName = [];
            res.data.forEach(e => {
              selectRolesId.push(e.role_id);
              this.roleName.push(e.name);
            })
          }
        })
        data.rolelist = selectRolesId;
        // 回显
        this.userForm = data;
      } else {
        // 添加
        this.userForm = {};
      }
      this.visible = value;
    }
  },
  watch: {
    value(val) {
      this.setCurrentValue(val);
    },
    visible(value) {
      this.$emit("input", value);
    }
  },
  mounted() {
    this.init();
  }
};
</script>

<style lang="less">
@import "../../../styles/table-common.less";
.drawer-content {
  overflow: auto;
}
.drawer-content::-webkit-scrollbar {
  display: none;
}
.user-title {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  .info-title {
    font-size: 16px;
    color: rgba(0, 0, 0, 0.85);
    display: block;
    margin-right: 16px;
  }
}
.info-header {
  font-size: 16px;
  color: rgba(0, 0, 0, 0.85);
  display: block;
  margin-bottom: 16px;
}
</style>

